# -*- coding: utf-8 -*-
import datetime
import json

import pytz
from django.contrib.sessions.backends.db import SessionStore
from django.contrib.sessions.models import Session
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse, JsonResponse


from services import TokenService
from models import TokenStore


class AccessTokenMiddleware(object):
    def __init__(self):
        # todo 中间件需要再次重写
        self.token = None
        self.user_session = None
        self.session_expire = None

    def process_request(self, request):
        request.token_store = {}
        if request.method == 'POST':
            self.token = request.POST.get('token', None)
            print 'access token middleware post'
        else:
            self.token = request.GET.get('token', None)
            print 'access token middleware get'

        if self.token is not None:
            try:
                self.user_session = TokenService()
                self.user_session.get(self.token)

                request.token_store = self.user_session.token_data
                print request.token_store
            except ObjectDoesNotExist:
                pass

    def process_response(self, request, response):
        print 'now is in middleware token'
        if self.user_session is None and len(request.token_store) > 0:
            print 'token is none'
            self.user_session = TokenService()
            self.user_session.token_data = request.token_store
            self.user_session.save()
            if isinstance(response, JsonResponse):
                response.content = self.setdefault_content(response.content,
                                                           'token', self.user_session.token_store.token_key)
        if self.token is not None:
            print 'token is not none'
            self.user_session.token_data = request.token_store
            self.user_session.save()
            if isinstance(response, JsonResponse):
                response.content = self.setdefault_content(response.content, 'token', self.token)

        self.__init__()
        request.token_store = {}
        return response

    @staticmethod
    def setdefault_content(content, key, value):
        json_content = json.loads(content)
        json_content[key] = value
        return json.dumps(json_content)
